"""
应用配置管理
从环境变量加载配置
"""
from pydantic_settings import BaseSettings
from typing import Optional, List
from pathlib import Path


class Settings(BaseSettings):
    """应用配置类"""
    
    # ==================== 应用配置 ====================
    APP_NAME: str = "AI智能体电商客服系统"
    APP_VERSION: str = "1.0.0"
    ENV: str = "development"
    DEBUG: bool = True
    SECRET_KEY: str = "dev-secret-key-change-in-production-min-32-chars"
    
    # ==================== 服务器配置 ====================
    HOST: str = "0.0.0.0"
    PORT: int = 8000
    RELOAD: bool = True
    API_PREFIX: str = "/api/v1"
    
    # ==================== PostgreSQL配置 ====================
    POSTGRES_HOST: str = "localhost"
    POSTGRES_PORT: int = 5432
    POSTGRES_DB: str = "agent_shop_db"
    POSTGRES_USER: str = "postgres"
    POSTGRES_PASSWORD: str = "your_password_here"
    
    # 数据库连接池配置
    DB_POOL_SIZE: int = 10
    DB_MAX_OVERFLOW: int = 20
    DB_POOL_TIMEOUT: int = 30
    DB_POOL_RECYCLE: int = 3600
    
    # ==================== Redis配置 ====================
    REDIS_HOST: str = "localhost"
    REDIS_PORT: int = 6379
    REDIS_PASSWORD: Optional[str] = None
    REDIS_DB: int = 0
    REDIS_CACHE_DB: int = 1
    REDIS_SESSION_DB: int = 2
    
    # Redis连接池配置
    REDIS_MAX_CONNECTIONS: int = 50
    REDIS_SOCKET_TIMEOUT: int = 5
    REDIS_SOCKET_CONNECT_TIMEOUT: int = 5
    
    # ==================== JWT认证配置 ====================
    JWT_SECRET_KEY: str = "jwt-secret-key-change-in-production-min-32-chars"
    JWT_ALGORITHM: str = "HS256"
    JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
    JWT_REFRESH_TOKEN_EXPIRE_DAYS: int = 7
    
    # ==================== OpenAI配置 ====================
    OPENAI_API_KEY: Optional[str] = None
    OPENAI_API_BASE: str = "https://api.openai.com/v1"
    OPENAI_MODEL: str = "gpt-3.5-turbo"
    OPENAI_TEMPERATURE: float = 0.7
    OPENAI_MAX_TOKENS: int = 2000
    OPENAI_TIMEOUT: int = 60
    
    # ==================== Embedding配置 ====================
    # 支持的Embedding提供商: openai, dashscope(千问), local
    EMBEDDING_PROVIDER: str = "dashscope"  # 默认使用本地模型
    
    # OpenAI Embeddings
    OPENAI_EMBEDDING_MODEL: str = "text-embedding-ada-002"
    
    # 千问/通义千问 Embeddings (DashScope)
    DASHSCOPE_API_KEY: Optional[str] = None
    DASHSCOPE_EMBEDDING_MODEL: str = "text-embedding-v2"  # 或 text-embedding-v1
    
    # 本地 Embeddings
    LOCAL_EMBEDDING_MODEL: str = "paraphrase-multilingual-MiniLM-L12-v2"
    
    # ==================== 向量数据库配置 ====================
    CHROMA_PERSIST_DIRECTORY: str = "./data/chromadb"
    CHROMA_COLLECTION_NAME: str = "knowledge_base"
    CHROMA_DISTANCE_METRIC: str = "cosine"
    
    # ==================== 知识库配置 ====================
    KNOWLEDGE_BASE_PATH: str = "../data/knowledge_base"  # 相对于backend目录
    CHUNK_SIZE: int = 600  # 优化分块大小,保持FAQ完整性
    CHUNK_OVERLAP: int = 150  # 增大重叠避免关键信息丢失
    MAX_SEARCH_RESULTS: int = 5
    RAG_SIMILARITY_THRESHOLD: float = 0.5  # 降低阈值,避免过滤掉相关文档
    
    # Rerank配置
    USE_RERANK: bool = True  # 是否启用Rerank精排
    RERANK_PROVIDER: str = "dashscope"  # rerank提供商
    RERANK_MODEL: str = "gte-rerank-v2"  # Rerank模型
    RERANK_RECALL_MULTIPLIER: int = 10  # 召回倍数
    RERANK_MIN_CANDIDATES: int = 10  # 最少候选数才启用rerank
    RERANK_TOP_N: int = 20  # Rerank返回的top-n结果
    
    # ==================== 对话配置 ====================
    MAX_CONVERSATION_HISTORY: int = 10
    CONVERSATION_MEMORY_TTL: int = 3600
    SESSION_TIMEOUT: int = 1800
    
    # ==================== Celery配置 ====================
    CELERY_BROKER_URL: str = "redis://localhost:6379/3"
    CELERY_RESULT_BACKEND: str = "redis://localhost:6379/4"
    CELERY_TASK_SERIALIZER: str = "json"
    CELERY_RESULT_SERIALIZER: str = "json"
    CELERY_TIMEZONE: str = "Asia/Shanghai"
    CELERY_ENABLE_UTC: bool = True
    
    # ==================== 日志配置 ====================
    LOG_LEVEL: str = "INFO"
    LOG_FILE: str = "./data/logs/app.log"
    LOG_ROTATION: str = "500 MB"
    LOG_RETENTION: str = "30 days"
    LOG_FORMAT: str = (
        "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | "
        "<level>{level: <8}</level> | "
        "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> - "
        "<level>{message}</level>"
    )
    
    # ==================== CORS配置 ====================
    CORS_ORIGINS: List[str] = [
        "http://localhost:5173",
        "http://localhost:3000",
        "http://127.0.0.1:5173",
    ]
    CORS_ALLOW_CREDENTIALS: bool = True
    CORS_ALLOW_METHODS: List[str] = ["*"]
    CORS_ALLOW_HEADERS: List[str] = ["*"]
    
    # ==================== API限流配置 ====================
    RATE_LIMIT_ENABLED: bool = True
    RATE_LIMIT_PER_MINUTE: int = 60
    RATE_LIMIT_PER_HOUR: int = 1000
    
    # ==================== WebSocket配置 ====================
    WS_HEARTBEAT_INTERVAL: int = 30
    WS_MAX_MESSAGE_SIZE: int = 1048576  # 1MB
    
    # ==================== 文件上传配置 ====================
    MAX_UPLOAD_SIZE: int = 10485760  # 10MB
    ALLOWED_UPLOAD_EXTENSIONS: List[str] = ["jpg", "jpeg", "png", "pdf", "docx"]
    
    # ==================== 监控配置 ====================
    ENABLE_METRICS: bool = True
    METRICS_PORT: int = 9090
    
    # ==================== Sentry配置 ====================
    SENTRY_DSN: Optional[str] = None
    SENTRY_ENVIRONMENT: str = "development"
    
    # ==================== 测试配置 ====================
    TEST_DATABASE_URL: Optional[str] = None
    
    # ==================== 属性方法 ====================
    
    @property
    def database_url(self) -> str:
        """获取数据库URL"""
        return (
            f"postgresql+asyncpg://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}"
            f"@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"
        )
    
    @property
    def sync_database_url(self) -> str:
        """获取同步数据库URL（用于Alembic）"""
        return (
            f"postgresql://{self.POSTGRES_USER}:{self.POSTGRES_PASSWORD}"
            f"@{self.POSTGRES_HOST}:{self.POSTGRES_PORT}/{self.POSTGRES_DB}"
        )
    
    @property
    def redis_url(self) -> str:
        """获取Redis URL"""
        if self.REDIS_PASSWORD:
            return f"redis://:{self.REDIS_PASSWORD}@{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
        return f"redis://{self.REDIS_HOST}:{self.REDIS_PORT}/{self.REDIS_DB}"
    
    def ensure_directories(self):
        """确保必要的目录存在"""
        directories = [
            Path(self.LOG_FILE).parent,
            Path(self.CHROMA_PERSIST_DIRECTORY),
            Path(self.KNOWLEDGE_BASE_PATH),
            Path("./data/uploads"),
        ]
        for directory in directories:
            directory.mkdir(parents=True, exist_ok=True)
    
    class Config:
        # 从项目根目录加载.env文件
        env_file = str(Path(__file__).parent.parent.parent / ".env")
        env_file_encoding = "utf-8"
        case_sensitive = True
        extra = "allow"  # 允许额外字段


# 全局配置实例
settings = Settings()

# 确保目录存在
settings.ensure_directories()


